package com.btpj.module_main.ui.nav

import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.btpj.jetpack.arouter.search.SearchServiceWrap
import com.btpj.jetpack.base.BaseFragment
import com.btpj.module_main.R
import com.btpj.module_main.adapter.NavItemAdapter
import com.btpj.module_main.data.entity.NavItem
import com.btpj.module_main.databinding.FragmentNavBinding
import kotlinx.android.synthetic.main.fragment_nav.*

class NavFragment : BaseFragment<NavViewModel, FragmentNavBinding>() {

    private val mAdapter by lazy { NavItemAdapter() }
    private lateinit var mViewPager2Adapter: FragmentStateAdapter
    private val mList: MutableList<NavItem> = ArrayList()

    companion object {

        @JvmStatic
        fun newInstance() = NavFragment()
    }

    override fun getLayoutId() = R.layout.fragment_nav

    override fun initView() {
        recycleView.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mAdapter
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            mAdapter.selectItemPosition = position
            viewPager2.setCurrentItem(position, true)
        }

        mViewPager2Adapter =
            object : FragmentStateAdapter(requireActivity().supportFragmentManager, lifecycle) {
                override fun getItemCount(): Int {
                    return mList.size
                }

                override fun createFragment(position: Int): Fragment {
                    return NavDataPageFragment.newInstance(mList[position].articles)
                }
            }
        mBinding.viewPager2.apply {
            offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            orientation = ViewPager2.ORIENTATION_VERTICAL
            registerOnPageChangeCallback(viewPager2CallBack)
            adapter = mViewPager2Adapter
        }

        cl_search.setOnClickListener { SearchServiceWrap.instance.start(requireContext()) }
    }

    override fun createObserve() {
        super.createObserve()
        mViewModel.navItemLiveData.observe(viewLifecycleOwner, Observer {
            mList.apply {
                clear()
                addAll(it)
            }
            mAdapter.setList(mList)
            mViewPager2Adapter.notifyDataSetChanged()
        })
    }

    private val viewPager2CallBack = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            mAdapter.selectItemPosition = position
            recycleView.scrollToPosition(position)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.viewPager2.unregisterOnPageChangeCallback(viewPager2CallBack)
    }
}